<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     <h1>主应用</h1>
    <button id="sendMsg">发送消息到沙箱</button>
    <!-- iframe 沙箱 -->
    <iframe
        id="sandBoxFrame"
        src="sandbox.html"
        sandbox="allow-scripts allow-same-origin"
        style="width: 100%; height: 300px; border: 1px solid #ccc;"
    ></iframe>
    <script>
        const sendBtn = document.getElementById('sendMsg')
        const iframe = document.getElementById('sandBoxFrame')

        // 发送消息给沙箱
        sendBtn.onclick = () => {
            iframe.contentWindow.postMessage({
                from: 'main',
                message: '来自主应用的消息'
            }, "*")
        }

        // 监听来自沙箱的消息
        window.addEventListener('message', (e) => {
            console.log('来自沙箱发送来的消息', e.data)
        })
    </script>
</body>
</html>